﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using KC.Constants;

namespace KC.Business.Net
{
	public static class Mail
	{
		public static bool SendMail(string to, string subject, string body)
		{
			// Validate params
			if (string.IsNullOrEmpty(to)) throw new ArgumentNullException("to");
			if (string.IsNullOrEmpty(subject)) throw new ArgumentNullException("subject");
			if (string.IsNullOrEmpty(body)) throw new ArgumentNullException("body");

			// Get & Validate config keys
			string
				from = ConfigurationManager.AppSettings["MailUser"],
				MailServer = ConfigurationManager.AppSettings["MailServer"],
				MailPass = ConfigurationManager.AppSettings["MailPass"];
			if (string.IsNullOrEmpty(from))
				throw new MissingFieldException("Config key MailUser missing");
			if (string.IsNullOrEmpty(MailServer))
				throw new MissingFieldException("Config key MailServer missing");
			if (string.IsNullOrEmpty(MailPass))
				throw new MissingFieldException("Config key MailPass missing");

			// Send mail
			using (MailMessage myMessage = new MailMessage(from, to, subject, body)) {
				SmtpClient myClient = new SmtpClient(MailServer);
				myClient.UseDefaultCredentials = false;
				myClient.Credentials = new System.Net.NetworkCredential(from, MailPass);
				myClient.DeliveryMethod = SmtpDeliveryMethod.Network;
				try {
					myClient.Send(myMessage);
					return true; }
				catch (SmtpException ex) {
					KC.Logging.Logger.Write("KC Architecture", ex, Logging.Logger.Severity.Warning);
					return false; }
				catch (Exception ex) {
					KC.Logging.Logger.Write("KC Architecture", ex, Logging.Logger.Severity.Error);
					return false;
				} 
			}
		}
	}
}
